<?php
namespace app\api\controller;
use x\my\Captcha;
use x\Xbase;
use x\my\Curl;
use Endroid\QrCode\QrCode;
class Com extends Xbase{

    //二维码
    public function qrcode(){
        $txt = $this->get('txt');
        $txt = urldecode($txt);
        $qrCode = new QrCode($txt);
        header('Content-Type: '.$qrCode->getContentType());
        echo $qrCode->writeString();
        exit;
    }

    //验证码
    public function captcha(){
        $token = $this->get('token');
        cookie('captcha_token',$token);
        return Captcha::generate($token);
    }

    //获取微信openid
    public function getWxOpenid(){
      $con  = c('api.wx_gzh_config')['myb'];
      //如果不是微信则直接返回
      if(!is_weixin()){
        cookie("wx_openid", null);
        exit('非微信浏览器');
      }
      //跳转地址
      $redirect_url = urlencode(url('com/getwxopenid'));
      //没有code,生成跳转连接地址
      if(!isset($_GET['code'])) {
        session('goback',$_SERVER['HTTP_REFERER']);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$con['app_id']."&redirect_uri=".$redirect_url."&response_type=code&scope=snsapi_base&state="."STATE" . "#wechat_redirect";
        r($url);
      //有code,则用curl获取 openid
      }else{
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$con['app_id']."&secret=".$con['secret']."&code=".$_GET['code']."&grant_type=authorization_code";
        $result = Curl::get($url);
        $rs = json_decode($result,true);
        cookie("wx_openid", $rs['openid']);
        r(session('goback'));
      }
    }
}
